<?php
namespace Home\Controller;

class PublicPageController extends ParentController {

    /**
     * 获取用户信息
     * @modify trainyao 2016-04-27    创建
     */
    public function getOpenid() {
        $wechatJSON = I('get.wechatJSON');
        $result = json_decode(stripslashes(htmlspecialchars_decode($wechatJSON)), true);
        $hotelId = I('get.hotel');

        $codeActiveTime = $result['expires_in'] + time();
        $codeActiveTime = date('Y-m-d H:i:s', $codeActiveTime);
        $userData['oauthid'] = $result['openid'];
        $userData['headpath'] = $result['headimgurl'];
        $userData['name'] = $result['nickname'];
        $userData['token'] = I('get.token');
        $userData['expiretime'] = $codeActiveTime;
        $userData['bindtime'] = time();

        $genderSwitch = array(
            '0' => '2',
            '2' => '0',
            '1' => '1',
        );
        $userData['gender'] = $genderSwitch[$result['sex']];  // 用户的性别，值为1时是男性，值为2时是女性，值为0时是未知

        $oauthId = $userData['oauthid'];
        $token = $userData['token'];

        $userAuthModel = D('UserAuth');
        $isBinded = $userAuthModel->getInfoByOauthType($oauthId, USER_OAUTH_TYPE_WECHAT_WEB);

        if(empty($isBinded)) {
            $name = $userData['name'];
            $name = filterEmoji($name);
            // 截取前20个字符
            $name = mb_substr($name, 0, 20, 'UTF-8');
            $gender = $userData['gender'];
            $headpath = $userData['headpath'];
            $expiretime = $userData['expiretime'];

            $addOauthResult = $userAuthModel->addInfo($oauthId, USER_OAUTH_TYPE_WECHAT_WEB, $token, $name, $gender, $headpath, $expiretime);

            session(C('USER_ID'), 0);
            session(C('USER_MOBILE'), '');
            session(C('USER_NAME'), $name);

            // 添加错误,log
            if(empty($addOauthResult)) {
                \Org\Util\FileLog::write("$name,$oauthId bind insert db false, from wechat web.", 1,  'Home/UserAuth');
                returnJson(500, 502, '系统繁忙，请稍后再试。');
                return;
            }
        } else {
            $userId = $isBinded['userlogin_id'];
            if ($userId == 0) {
                // 未绑定手机号
                session(C('USER_ID'), 0);
                session(C('USER_MOBILE'), '');
                session(C('USER_NAME'), $isBinded['name']);
            } else {
                $userLoginModel = D('UserLogin');
                $userLoginInfo = $userLoginModel->getInfo($userId);

                session(C('USER_ID'), $userId);
                session(C('USER_AREACODE'), $userLoginInfo['areacode']);
                session(C('USER_MOBILE'), $userLoginInfo['mobile']);
                session(C('USER_NAME'), $userLoginInfo['name']);
            }
        }

        session(C('WECHAT_OAUTH_LOGIN'), 1);
        session(C('WECHAT_LOGIN_OPEN_ID'), $oauthId);
        session(C('AUTH_LOGIN_TYPE'), USER_OAUTH_TYPE_WECHAT_WEB);

        redirect('/Home/BookPage/index?hotel='.$hotelId);
    }
}